package bservice

import (
    "github.com/micro/go-micro/v2/config"
    "github.com/micro/go-plugins/config/source/consul/v2"
    "gonaio_base/constant"
)

func (Service) GetConfigHandle() (handle config.Config, err error) {
    source := consul.NewSource(
        consul.WithAddress(bconstant.CONSUL_ADDRESS),
        consul.WithPrefix(bconstant.CONSUL_PREFIX),
        consul.StripPrefix(true),
    )
    handle, err = config.NewConfig()
    if err != nil {
        return
    }
    err = handle.Load(source)
    return
}

func (Service) WatchConfig(f func()) (err error) {
    source := consul.NewSource(
        consul.WithAddress(bconstant.CONSUL_ADDRESS),
        consul.WithPrefix(bconstant.CONSUL_PREFIX),
        consul.StripPrefix(true),
    )
    handle, err := config.NewConfig()
    if err != nil {
        return
    }
    err = handle.Load(source)
    if err != nil {
        return
    }
    watcher, err := handle.Watch()
    if err != nil {
        return
    }
    for {
        _, err = watcher.Next()
        if err != nil {
            return
        }
        f()
    }
}
